<template>
  <div class="flex-d-col h-100%">
    <div class="app-main-container h-100% flex">
      <div class="left flex-d-col">
        <!-- <div class="title">规章目录</div> -->
        <organizeQuestionBanks
          @ac-tree-data="
            (val, arr) => {
              leftData = arr;
              getTreeData(val);
            }
          "
        ></organizeQuestionBanks>
      </div>
      <div class="right flex-d-col flex-1 ml-20px">
        <div class="title">规章列表</div>
        <div class="flex-d-col h-100%">
          <div class="search">
            <el-form :inline="true" :model="formSearch" size="small">
              <el-form-item>
                <el-input
                  v-model="formSearch.name"
                  class="w-200px"
                  placeholder="输入搜索关键词"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button
                  type="primary"
                  @click="getTreeData({ id: addEditVisible.data.orgId })"
                  >搜索</el-button
                >
                <el-button
                  @click="
                    (formSearch.name = ''), getTreeData({ id: addEditVisible.data.orgId })
                  "
                  >重置</el-button
                >
              </el-form-item>
            </el-form>
          </div>
          <div class="search-con flex-1">
            <!-- <div class="flex-x-between">
              <div></div>
              <div class="btn" v-if="addEditVisible.data.orgId">
                <el-button type="primary" size="small" @click="addEdit('add')"
                  >添加</el-button
                >
              </div>
            </div> -->
            <el-table
              :data="tableData.data"
              style="width: 100%"
              max-height="320"
              fit
              :highlight-current-row="!props.multiple"
              @current-change="
                (val) => {
                  return !props.multiple ? handleSelectionChange(val ? [val] : []) : '';
                }
              "
              @selection-change="
                (val) => {
                  return props.multiple ? handleSelectionChange(val) : '';
                }
              "
            >
              <el-table-column v-if="props.multiple" type="selection" width="55" />
              <el-table-column prop="name" label="规章名称" />
              <el-table-column prop="publishTime" label="最新发布时间" />
              <el-table-column prop="isActive" label="版本状态">
                <template #default="scope">
                  <el-text :type="scope.row.isActive ? 'success' : 'info'">{{
                    scope.row.isActive ? "启用" : "停用"
                  }}</el-text>
                </template>
              </el-table-column>
              <!-- <el-table-column prop="address" label="操作">
                <template #default="scope">
                  <el-button type="primary" size="small" link>添加</el-button>
                  <el-popconfirm title="确定删除？">
                    <template #reference>
                      <el-button type="danger" size="small" link>删除</el-button>
                    </template>
                  </el-popconfirm>
                </template>
              </el-table-column> -->
            </el-table>
            <!-- <div class="w-100%"> -->
            <!-- </div> -->
          </div>
          <el-pagination
            class="flex-x-center mt-10px"
            small
            background
            layout="prev, pager, next"
            v-model:current-page="page.index"
            :page-size="page.size"
            :total="page.total"
            hide-on-single-page
            @current-change="pageChange"
          />
        </div>
      </div>
    </div>
    <el-dialog
      v-model="addEditVisible.show"
      :title="addEditVisible.title"
      width="400"
      :before-close="handleClose"
    >
      <el-form
        ref="RefForm"
        :model="addEditVisible.data"
        label-width="120"
        class="w-100%"
        :rules="rules"
      >
        <el-form-item label="上传规章文件" prop="fileId">
          <el-upload
            ref="upload"
            v-model:file-list="fileList"
            action="/dev-api/api/app/file/upload-file"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            :on-exceed="handleExceed"
            :limit="1"
            class="w-200px"
          >
            <el-button type="primary">
              <el-icon><Upload /></el-icon>
              上传
            </el-button>
          </el-upload>
          <el-input class="hidden" v-model="addEditVisible.data.fileId"></el-input>
        </el-form-item>
        <el-form-item label="规章名称" prop="name">
          <el-input
            v-model="addEditVisible.data.name"
            class="w-200px"
            placeholder=""
          ></el-input>
        </el-form-item>
        <el-form-item label="发布日期" prop="publishTime">
          <el-date-picker
            v-model="addEditVisible.data.publishTime"
            type="date"
            class="w-200px!"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addEditClose">取消</el-button>
          <el-button type="primary" @click="addEditSave"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useRoute, useRouter } from "vue-router";
import { ApiUploadFile } from "@/api/file";
import {
  ApiPostRegulation,
  ApiGetRegulation,
} from "@/api/resource-management/regulations";
import { Search } from "@element-plus/icons-vue";
import organizeQuestionBanks from "@/components/organizeQuestionBanks/index.vue";
import type {
  UploadRawFile,
  UploadRequestOptions,
  UploadUserFile,
  UploadFile,
  UploadProps,
  UploadInstance,
  FormInstance,
  FormRules,
} from "element-plus";
import { genFileId, dayjs } from "element-plus";

const route = useRoute();
const router = useRouter();

const { params, query } = route;
const { path } = params;

const props = defineProps({
  // 过滤条件
  // isActive: 是否为激活启动状态
  filter: {
    default: () => {},
  },
  // 是否多选
  // default: true 多选 ， false 单选
  multiple: {
    type: Boolean,
    default: false,
  },
});

let leftData = {};

const formSearch = reactive({
  name: "",
});

const addEditVisible = reactive({
  show: false,
  title: "添加规章",
  data: {},
});
const RefForm = ref(null);
const rules = reactive({
  fileId: [{ required: true, message: "规章文件必填", trigger: "change" }],
  name: [{ required: true, message: "规章名称必填", trigger: "change" }],
  publishTime: [{ required: true, message: "发布日期必填", trigger: "change" }],
});
// 添加试题
const addEdit = (type, editId = null) => {
  if (type == "add") {
    addEditVisible.title = "添加规章";
  }
  addEditVisible.show = true;
};

// 上传成功
const handleSuccess = (res) => {
  if (res.code == 200) {
    addEditVisible.data.name = res.data.fileName.replace(/\.[^/.]+$/, "");
    addEditVisible.data.fileId = res.data.id;
  }
};
const addEditSave = () => {
  RefForm.value.validate((valid, fields) => {
    if (valid) {
      ApiPostRegulation(addEditVisible.data).then((res) => {
        if (res.code == 200) {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          addEditClose();
        }
      });
    }
  });
};
const upload = ref<UploadInstance>();
const handleExceed: UploadProps["onExceed"] = (files) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};
const handleRemove = () => {
  addEditVisible.data.fileId = "";
};
const addEditClose = () => {
  let orgId = addEditVisible.data.orgId;
  addEditVisible.data = {};
  addEditVisible.data.orgId = orgId;
  addEditVisible.show = false;
};
// setTimeout(() => {
//   console.log(import.meta.env.VITE_APP_BASE_API);
// }, 1000);

// 分页
const page = reactive({
  index: 1,
  size: 10,
  total: 0,
});
const pageChange = (val) => {
  page.index = val;
  getTreeData({ id: addEditVisible.data.orgId });
};

const getTreeData = (val) => {
  addEditVisible.data.orgId = val?.id;
  if (val?.id) {
    let params = {
      railwayBureau: null,
      trainDepotName: null,
      stationName: null,
      keyWord: "",
      enable: null,
      pageIndex: page.index,
      pageSize: page.size,
      ...leftData,
    };
    ApiGetRegulation(params).then((res) => {
      if (res.code == 200) {
        tableData.data = res.data.data.map((e) => {
          return {
            ...e,
            publishTime: dayjs(e.publishTime).format("YYYY-MM-DD"),
          };
        });
        page.total = res.data.dataCount;
      }
    });
  }
};
// 规章列表
const tableData = reactive({
  data: [],
  totalCount: 0,
});

const emits = defineEmits(["acData"]);
// table选中数据
const handleSelectionChange = (data) => {
  // debugger;
  // 数组形式
  emits("acData", data);
};
</script>

<style scope lang="scss">
.app-main-container {
  overflow: hidden;
  .title {
    font-family: Source Han Sans CN, Source Han Sans CN;
    font-weight: bold;
    font-size: 16px;
    color: rgba(0, 0, 0, 0.9);
    line-height: 21px;
    text-align: left;
    font-style: normal;
    text-transform: none;
    margin-bottom: 20px;
  }
  .left {
    height: 100%;
  }
  .right {
    & > .flex-d-col {
      background: linear-gradient(180deg, #ffffff 0%, rgba(255, 255, 255, 0.8) 100%);
      border-radius: 20px 20px 20px 20px;
      border: 1px solid rgba(4, 42, 94, 0.1);
      padding: 20px;
    }
    .el-input {
      &-group__append,
      &-group__prepend {
        padding: 0 10px;
      }
    }
    .con {
      border: 1px solid rgba(0, 57, 137, 0.1);
      border-radius: 20px 20px 0px 0px;
      padding: 10px 20px 20px;
      .el-checkbox-group {
        font-size: 14px;
        line-height: inherit;
      }
      .list {
        .title {
          margin-bottom: 10px;
        }
        .type {
          background-color: #1759b5;
          font-size: 12px;
          padding: 4px 8px;
          border-radius: 6px;
          color: #fff;
        }
        .answer {
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
          pointer-events: none;
        }
        .source {
          border: 1px solid rgba(0, 0, 0, 0.1);
          padding: 8px;
          border-radius: 10px;
          font-size: 12px;
          color: rgba(0, 0, 0, 0.6);
        }
      }
    }
  }
}
</style>
